﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Controls;
//using System.Windows.Forms;
using System.Windows.Documents;
using System.Collections;

using TIMETABLEASY;

using TIMETABLEASY.TokenAuthentification;
//http://webman.developpez.com/articles/aspnet/file/csharp/
//http://fr.wikipedia.org/wiki/ICalendar

namespace TIMETABLEASY.iCalManager
{
    class ICalManager
    {
        //Attributs
        private StreamWriter sw;
        private string file_name;
        private DateTime date_begin, date_end;
        private ListBox list_cal;

        //Creator
        public ICalManager(DateTime begin, DateTime end, ListBox lst)
        {
            date_begin = begin;
            date_end = end + TimeSpan.FromHours(23);
            list_cal = lst;
 
            if (get_save_path())
            {
                sw = new StreamWriter(file_name);
                create_ical_file();
                sw.Close();
            }
        }

        //Public Methods
        public void create_ical_file()
        {
            //recreate_file();
            write_header();
            write_events();
            write_footer();
        }

        /* Create the header calendar
         * 
            BEGIN:VCALENDAR
            VERSION:2.0
            PRODID:-//hacksw/handcal//NONSGML v1.0//EN
         */
        private void write_header()
        {
            try
            {   //Open the file
                sw.WriteLine("BEGIN:VCALENDAR");
                sw.WriteLine("VERSION:2.0");
                sw.WriteLine("PRODID:-//hacksw/handcal//NONSGML v1.0//EN");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /* Create the events calendar
         * 
            BEGIN:VEVENT
            DTSTART:19970714T170000Z
            DTEND:19970715T035959Z
            SUMMARY:Bastille Day Party
            END:VEVENT
         */
        private void write_events()
        {
            dbDataContext db_remote = new dbDataContext();;
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            string classe_user = "Class -" + token.User_classe;
                        
            try
            {
                IEnumerator enumerator = (list_cal.SelectedItems).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (enumerator.Current.ToString() == "Class -" + token.User_classe) 
                    {
                        foreach (events s in (from e in db_remote.events
                                                  where e.T_begin > date_begin && e.T_begin < date_end
                                                  && e.type != "Personal" && e.campus == token.User_campus && e.classe == token.User_classe
                                                  select e))
                        {
                            write_event(s);
                        }
                    }

                    if (enumerator.Current.ToString() == "Prof planning")
                    {
                        foreach (events s in (from e in db_remote.events
                                                  where e.T_begin > date_begin && e.T_begin < date_end
                                                  && e.type != "Personal" && e.id_person == token.User_id && e.type_person == token.User_level
                                                  select e))
                        {
                            write_event(s);
                        }
                    }

                    if (enumerator.Current.ToString() == "Personal")
                    {
                        foreach (events s in (from e in db_remote.events
                                      where e.T_begin > date_begin && e.T_begin < date_end
                                      && e.type == "Personal" && e.id_person == token.User_id && e.type_person == token.User_level
                                      select e))
                        {
                            write_event(s);
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void write_event(events s)
        {

            event_management event1 = new event_management();
            string name_person = event1.give_me_name((int)s.id_person, s.type_person);

            sw.WriteLine("BEGIN:VEVENT");
            sw.WriteLine("DTSTART:{0}{1}{2}T{3}{4}{5}Z",
                            s.T_begin.Year.ToString(), double_char(s.T_begin.Month), double_char(s.T_begin.Day),
                            double_char(s.T_begin.Hour), double_char(s.T_begin.Minute), double_char(s.T_begin.Second));

            sw.WriteLine("DTEND:{0}{1}{2}T{3}{4}{5}Z",
                             s.T_end.Year.ToString(), double_char(s.T_end.Month), double_char(s.T_end.Day),
                             double_char(s.T_end.Hour), double_char(s.T_end.Minute), double_char(s.T_end.Second));

            sw.WriteLine("SUMMARY:{0}", s.name);

            sw.WriteLine("LOCATION:{0}", s.room_id);
            sw.WriteLine("CATEGORIES:{0}", s.type);
            sw.WriteLine("DESCRIPTION:rajouter blabla avec prof {0}", name_person);
            sw.WriteLine("END:VEVENT");
        }

        /* Create the footer calendar
         * 
            END:VCALENDAR
         */
        private void write_footer()
        {
            try
            {   
                sw.WriteLine("END:VCALENDAR");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private string double_char(int nb)
        {
            if (nb < 10)
                return "0" + nb.ToString();
            else
                return nb.ToString();

        }

        private bool get_save_path()
        {
            Microsoft.Win32.SaveFileDialog dlg_path2save = new Microsoft.Win32.SaveFileDialog();
            SingletonTokenUser token = SingletonTokenUser.GetInstance();

            dlg_path2save.FileName = token.User_surname + "'calendar";
            dlg_path2save.DefaultExt = ".ics";
            dlg_path2save.Filter = "iCal File (.ics)|*.ics";

            Nullable<bool> result = dlg_path2save.ShowDialog();

            if( result == true) 
            {
                file_name = dlg_path2save.FileName;
            }

            return (bool) result;
        }

    }
}
